<template>
  <basic-container>
    <el-form ref="form" searchform :model="form" label-width="80px" @submit.native.prevent>
    <el-row>
      <el-col :span="5" style="min-width:240px">
        <div class="text" style="width: 70px">审核状态:</div>
        <el-select id="id-offer-creative-handleUploadToYoutube-isShowSelectOptions" v-model="form.auditStatus" clearable size="mini" placeholder="请选择审批状态" style="width: 150px"
                   ref="auditAuditStatus" @visible-change="isShowSelectOptions" @change="searchForm">
          <el-option
            v-for="item in auditStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="5" style="min-width:240px">
        <div class="text" style="width: 70px">提交人:</div>
        <el-input
          id="id-offer-creativeaudit-handleUploadToYoutube-searchForm-one"
          placeholder="请输入提交人"
          v-model="form.submitUsername"
          clearable
          size="mini"
          style="width: 150px" @keyup.enter.native = "searchForm">
        </el-input>
      </el-col>
      <el-col :span="5" style="min-width:240px">
        <div class="text" style="width: 70px">审核人:</div>
        <el-input
          id="id-offer-creativeaudit-handleUploadToYoutube-searchForm"
          placeholder="请输入审核人"
          v-model="form.auditor"
          clearable
          size="mini"
          style="width: 150px" @keyup.enter.native = "searchForm">
        </el-input>
      </el-col>
      <el-col :span="4" style="min-width: 240px;margin-top: -6px;">
      <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-unfoldIcon"
                   :class="upIcon" disabled class="search-circle"></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="清空" placement="top">
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-emptyForm"
                   :class="emptyIcon" class="search-circle" @click="emptyForm"></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="搜索" placement="top">
        <el-button id="id-offer-creative-handleUploadToYoutube-searchForm-two"
                   type="primary" icon="el-icon-search" size="small" @click="searchForm" style="margin-right: 0">搜索</el-button>
      </el-tooltip>
    </el-col>
    </el-row>
    </el-form>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :row-class-name-rollback="getRowClassName"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-exportExcel"
                   type="primary"
                   size="small"
                   icon="el-icon-download" @click="exportExcel">导 出</el-button>
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-rollbackCreativeAudit"
                   type="primary"
                   size="small"
                   v-if="userInfo.is_agency == 1 && (roles.admin || roles.agc_customer_manager)"
                   :disabled="!(rollbackCreativeAuditIdList.length > 0)"
                   icon="el-icon-refresh-left" @click="rollbackCreativeAudit">重 审</el-button>
      </template>
      <template slot-scope="{row}" slot="auditor">
        <div v-if="row.originAuditId === -1 && row.auditCreative === 1">{{ row.customerName }}</div>
        <div v-else>{{ row.auditor }}</div>
      </template>
      <!--<template slot-scope="{type,size,row}" slot="submitUsername">
        <div v-if="row.originAuditId !== -1 && row.auditCreative === 1">{{ row.agencyName }}</div>
        <div v-else>{{ row.submitUsername }}</div>
      </template>-->
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button
          id="id-offer-creativeaudit-handleUploadToYoutube-handleEdit"
          v-if="!isAdvSharedOffer && row.hasEditPem && (roles.admin || roles.operator || roles.optimizer )&& row.auditStatus !== 1 && !isAuditTimeout(row)"
          icon="el-icon-edit" :size="size"
          :type="type" @click="handleEdit(row)">编 辑
        </el-button>
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-handleCheck"
                   icon="el-icon-s-check" :size="size" :type="type" @click="handleCheck(row)">查 看</el-button>
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-isCopyEnable"
                   v-show="!isAdvSharedOffer && isCopyEnable(row)"
                   icon="el-icon-document-copy" :size="size" :type="type" class="copy"
                   @click="handleCopy(row)">复制链接
        </el-button>
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-handleCopy"
                   v-if="!isAdvSharedOffer && isRefreshTimeoutEnable(row) && getRefresh()"
                   icon="el-icon-document-copy" :size="size" :type="type" class="copy"
                   @click="handleCopy(row,'refresh')">刷新审核
        </el-button>
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-handleReleaseAuditCreative"
                   v-if=" !isAdvSharedOffer && isReleaseEnable(row) && getRelease()"
                   icon="el-icon-document-copy" :size="size" :type="type" class="copy"
                   @click="handleReleaseAuditCreative(row)">释放素材
        </el-button>
        <el-button id="id-offer-creativeaudit-handleUploadToYoutube-handleExamine"
                   v-if="row.hasAuditPem && row.auditStatus !== 1 && !isAuditTimeout(row)"
                   icon="el-icon-s-order" :size="size" :type="type" @click="handleExamine(row)">审 核
        </el-button>
        <!-- && row.auditCreative === 1 && (userInfo.is_agency === 1 ? true : (roles.admin || roles.operator))-->
      </template>
    </avue-crud>
    <!--复制链接-->
    <el-dialog title="复制审核链接" width="60%" center :visible.sync="copyDialog" :modal-append-to-body="false"
               :append-to-body="true" :close-on-click-modal="false">
      <div>
        <div id="link"> 链接 : {{ copyKeyUrl }}</div>
        <div style="width: 160px;margin: 0 auto;margin-top: 20px" slot="footer" class="dialog-footer">
          <el-button id="id-offer-creativeaudit-copy" @click="copy" size="mini">复制链接</el-button>
          <el-button id="id-offer-creativeaudit-copyDialog" @click="copyDialog = false" size="mini">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--编辑-->
    <el-dialog :title="title" :visible.sync="visible" modal-append-to-body="false"
               :close-on-click-modal="false" :before-close="handleClose"
               :append-to-body="true" v-if="visible" width="80%">
      <creative-audit-detail :useType="useType" :dataList="dataList"></creative-audit-detail>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, copyLink,/*updateStatus,updateCreativeStatus,*/ releaseAuditCreative, rollbackCreativeAudit, exportExcel} from "@/api/offer/creativeaudit";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {mapGetters} from "vuex";
import creativeAuditDetail from "./components/creativeAuditDetail";
import { createEventHandler } from "@/util/events";
import { createWebSocket } from "@/util/ws";
import store from '@/store/'
import permission from "@/views/util/permission";

export default {
  components: {
    creativeAuditDetail
  },
  data() {
    return {
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      copyDialog: false,
      copyKeyUrl: '',
      title: '',//弹窗标题
      visible: false,//开关
      form: {
        auditStatus: null,
        submitUsername: null,
        auditor: null,
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        offerId: '',
        total: 0
      },
      useType: '',//审核页面使用类型
      dataList: null,
      selectionList: [],
      auditStatus: [
        {label: '待审核', value: 0},
        {label: '完成', value: 1},
        {label: '已过期', value: 3},
      ],
      option: {
        // height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        excelBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: 'id',
            prop: "id",
            overHidden:true,
          },
          {
            label: "名称",
            prop: "name",
            overHidden:true,
          },
          {
            label: "审核状态",
            prop: "auditStatus2",
            dicData: [
              {label: '待审核', value: 0},
              {label: '完成', value: 1},
              {label: '已过期', value: 3},
            ],
            type: 'select',
          },
          {
            label: "图片数量",
            prop: "imgCount",
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }]
          },
          {
            label: "视频数量",
            prop: "vidCount",
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }]
          }, {
            label: "提交人",
            searchSize: "mini",
            prop: "submitUsername",
          },
          {
            label: "提交时间",
            prop: "submittedTime",
            rules: [{
              required: true,
              message: "请输入提交时间",
              trigger: "blur"
            }],
            overHidden:true,
          },
          {
            label: "审核时间",
            prop: "approvedTime",
            rules: [{
              required: true,
              message: "请输入审核时间",
              trigger: "blur"
            }],
            overHidden:true,
          },
          {
            label: "审核人",
            searchSize: "mini",
            prop: "auditor",
            overHidden:true,
          },
        ]
      },
      data: [],
      currOpRowId: '',
      isAdvSharedOffer: false,
    };
  },
  computed: {
    ...mapGetters(["permission", "roles", "userInfo","offer"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.creativeaudit_add, false),
        viewBtn: this.vaildData(this.permission.creativeaudit_view, false),
        delBtn: this.vaildData(this.permission.creativeaudit_delete, false),
        editBtn: this.vaildData(this.permission.creativeaudit_edit, false),
        excelBtn: this.vaildData(this.roles.admin || this.roles.operator, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    rollbackCreativeAuditIdList() {
      let ids = [];
      this.selectionList.forEach(ele => {
        if(ele.auditStatus == 1 && ele.hasCopyLinkPem) {
          ids.push(ele.id);
        }
      });
      return ids;
    },
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if(self.socket) {
      self.socket.close();
      self.socket = null;
    }
    if(self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },
  created() {
    //window.addEventListener('keyup', this.searchForm) //监听键盘事件
    let self = this;
    this.eventHandler = createEventHandler("offerCenter")
      .addListener((event) => {
        if(event.message == 'offerChanged' && event.offerId && event.offerId !== "" ) {
        self.page.offerId = event.offerId;
        self.onLoad(self.page);
        self.updateIsAdvSharedOffer();
      }
    });
    this.page.offerId = store.state.user.offer;
    this.updateIsAdvSharedOffer();

    self.isRefreshing = false;
    if(!self.socket) {
      self.socket = createWebSocket('/api/blade-system/wss','json');
      if(self.socket) self.socket.ontextmessage = (msg)=>{
        let msgObj = JSON.parse(msg);
        //console.log("socket receive:" + msg)
        if(msgObj) {
          if(!self.isRefreshing && msgObj.messageName === 'tenantMessage' && msgObj.data.messageName === 'creativeAuditChanged' && msgObj.data.offerId == self.page.offerId) {
            if(msgObj.data.creativeAuditIds != null) {
              let creativeAuditIdList = msgObj.data.creativeAuditIds.split(',');
              if(self.data.find((v)=>{return (creativeAuditIdList.includes(v.id));}) == null) {
                return;
              }
            }
            self.isRefreshing = true;
            //不可以频繁刷新，如果有刷新需求，延迟5秒刷新，在延迟期间，有新的刷新需求均不会多次触发onLoad
            setTimeout(() => {
              self.onLoad(self.page);
              self.isRefreshing = false;
            },5000);
          }
        }
      };
      if(self.socket) self.socket.onerror = ()=>{
        this.$message({
          type: 'warning',
          message: '您的网络目前不稳定，数据可能不能自动刷新！'
        });
      };
    }
  },
  methods: {
    isShowSelectOptions(isShowSelectOptions){
      if(!isShowSelectOptions) this.$refs.auditAuditStatus.blur();
    },
    //搜索按钮函数
    searchForm(){
      this.query = this.form
      this.page.currentPage = 1
      this.onLoad(this.page,this.form)
    },
    //清空按钮函数
    emptyForm(){
      this.form = {
        auditStatus: null,
        submitUsername: null,
        auditor: null,
      }
      this.query = this.form
      this.onLoad(this.page,this.form)
    },
    getRealUrl(url) {
      if(url == null) {
        return url;
      }
      let loc = window.location;
      let realUrl = url;
      if(realUrl.indexOf("//") > 0) {
        let hostStart = realUrl.indexOf("//") + 2;
        let hostEnd = realUrl.indexOf("/",hostStart);
        if(hostStart >= 7 && hostEnd > hostStart) {
          realUrl = loc.protocol + "//" + loc.host + realUrl.substring(hostEnd);
        }
      }
      return realUrl;
    },
    /**
     * 复制链接
     */
    copy(){
      var input = document.createElement('input')
      //将input的值设置为需要复制的内容
      input.value =  this.copyKeyUrl;
      //添加input标签
      document.body.appendChild(input)
      //选中input标签
      input.select()
      //执行复制
      document.execCommand('copy')
      //成功提示信息
      this.$message.success('复制成功!')
      //移除input标签
      document.body.removeChild(input)

      setTimeout(()=>{
        this.copyDialog = false
      },2000);
    },
    updateIsAdvSharedOffer() {
      let self = this;
      if(self.userInfo.is_agency == 0) {
        self.loadOfferInfo(self.page.offerId,(offerInfo)=>{
          if(offerInfo) {
            self.isAdvSharedOffer = (offerInfo.isShared == 1);
          } else {
            self.isAdvSharedOffer = false;
          }
        });
      } else {
        self.isAdvSharedOffer = false;
      }
    },
    loadOfferInfo(offerId,success) {
      if(offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res)=>{
          success(res.data.data);
        }).catch(()=>{
          success(null);
        });
      }
    },
    handleExamine(row) {
      this.currOpRowId = row.id;
      this.title = '素材审核'
      this.useType = 'examine'
      this.dataList = {listId: row.id, offerId: store.state.user.offer}
      this.visible = true
    },

    //关闭弹窗
    handleClose() {
      this.visible = false
      this.onLoad(this.page, store.state.user.offer);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page, store.state.user.offer);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        if(error)
          loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDown() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
    },
    handleEdit(row) {
      this.currOpRowId = row.id;
      this.title = '编辑素材审核'
      this.useType = 'edit'
      this.dataList = {listId: row.id, offerId: store.state.user.offer}
      this.visible = true
    },

    handleCheck(row) {
      this.currOpRowId = row.id;
      this.title = '查看素材审核信息'
      this.useType = 'check'
      this.dataList = {listId: row.id, offerId: store.state.user.offer}
      this.visible = true
    },

    isCopyEnable(row) {
      if(row.auditCreative === 1 && this.userInfo.is_agency === 1 && row.hasCopyLinkPem && row.auditStatus === 0) {
        console.log()
        return (((new Date()) - new Date(row.submittedTime.replace(/\-/g, "/"))) <= 86400000);
      } else {
        return false;
      }
    },
    isRefreshTimeoutEnable(row) {
      if(row.auditStatus === 0) {
        return (((new Date()) - new Date(row.submittedTime.replace(/\-/g, "/"))) > 86400000);
      }
      return false;
    },
    isReleaseEnable(row) {
      if(row.auditStatus === 0) {
        return (((new Date()) - new Date(row.submittedTime.replace(/\-/g, "/"))) > 86400000);
      }
      return false;
    },
    getRefresh(){
      if(this.permission.hasOwnProperty('creativeaudit_Refresh')){
        return true
      }else {
        return false
      }
    },
    getRelease(){
      if(this.permission.hasOwnProperty('creativeaudit_release')){
        return true
      }else {
        return false
      }
    },
    isAuditTimeout(row) {
      if(row.auditStatus === 3) {
        return true;
      }
      if(row.auditStatus === 0) {
        return (((new Date()) - new Date(row.submittedTime.replace(/\-/g, "/"))) > 86400000);
      }
      return false;
    },
    handleCopy(row, opType) {
      this.currOpRowId = row.id;
      copyLink(row.id, opType).then(res => {
        if (res.data.code === 200) {
          if (res.data.success === true) {
            this.copyKeyUrl = this.getRealUrl(res.data.data.keyLink)
            if(opType == "refresh") {
              let nowDate = new Date();
              row.submittedTime = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) + "-" + nowDate.getDate() + " " + nowDate.getHours() + ":" + nowDate.getMinutes() + ":" + nowDate.getSeconds();
              row.auditStatus2 = 0;
            }
            if(this.isCopyEnable(row)) {
              this.copyDialog = true
            }
          } else {
            this.$message.warning(res.data.msg);
          }
        }
      })
    },
    handleReleaseAuditCreative(row) {
      this.currOpRowId = row.id;
      releaseAuditCreative(row.id).then(res => {
        if (res.data.code === 200) {
          if (res.data.success === true) {
            row.auditStatus = 3;
            row.auditStatus2 = 3;
            this.$message.info("成功释放素材！");
          } else {
            this.$message.warning(res.data.msg);
          }
        }
      })
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      // updateStatus(this.offer);
      // updateCreativeStatus();
      this.onLoad(this.page, this.query);
    },
    rollbackCreativeAudit() {
      rollbackCreativeAudit(this.rollbackCreativeAuditIdList.join(",")).then(res=>{
        if (res.data.success === true) {
          this.$message.success("素材审核重审成功！");
        } else {
          this.$message.warning("未发现可重审的素材审核！");
        }
      }).catch(()=>{
        this.$message.error("素材审核重审失败！");
      });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, page.offerId, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.data.forEach((row)=>{
          row.auditStatus2 = row.auditStatus;
          if(row.auditStatus !== 3 && this.isAuditTimeout(row)) {
            row.auditStatus2 = 3;
          }
        })
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    getRowClassName({row,rowIndex}) {
      if(row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    exportExcel() {
      this.$confirm("是否导出" + (this.ids ? "选中" : "全部") + "数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        exportExcel(this.page.offerId, this.query, this.ids).then(res => {
          let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          let url = window.URL.createObjectURL(new Blob([res.data]))
          let link = document.createElement("a")
          link.style.display = "none"
          link.href = url
          link.download = filename
          document.body.appendChild(link)
          link.click()
        })
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  /deep/.current-op-row {
    background-color: #f5dab1;
  }
  .text{
    width: 45px;
    height:30px;
    float: left;
    font-size: 13px;
    margin-top: 3px;
    color: #72767b
  }
  .search-circle{
    border-radius: 50%;
    border: 1px solid #dcdfe6;
    width: 30px;
    height: 30px;
    padding: 0;
    margin-right: 0;
  }
</style>
